#include "threadPool.h"
#include "train.h"

int recvn(int sockfd,void *buf,int length);
//void get_salt(char *salt,char *passwd){
//   int len = strlen(passwd);
//   int  fre = 0;
//   int start;
//   int end;
//   int t = 0;
//   for(int i = 0;i<len;i++){
//       if(passwd[i] == '$'){
//           fre++;
//       }
//       if(fre == 1){
//           start = i;
//       }
//       if(fre > 0 && fre < 3){
//           salt[t] = passwd[i];
//       }
//       if(fre == 3){
//           end = i;
//           break;
//       }
//   }
//   salt[t] = '\0';   
//}

void get_salt(char *salt,char *passwd)
{
    int i,j;
    for(i=0,j=0;passwd[i] && j != 3;++i)
    {
        if(passwd[i] == '$')
            ++j;
    }
    strncpy(salt,passwd,i-1);
}

int userCheck(int netfd){
    while(1){
        struct spwd *sp;
        char passwd[500];
        char salt[512]={0};
        char username[1024];
        //接受一个用户名
        train_t train;
        recvn(netfd,&train.len,sizeof(int));
        recvn(netfd,train.data,train.len);
        memcpy(username,train.data,train.len); 
        if((sp=getspnam(username))==NULL){
            int t = -1;
            write(netfd,&t,sizeof(int));
            continue;
        }else{
            int t=1;
            write(netfd,&t,sizeof(int));
        }

        get_salt(salt,sp->sp_pwdp);
        //发送盐值
        write(netfd,&salt,12);
        //接受密文
        bzero(&train,sizeof(train));
        recvn(netfd,&train.len,sizeof(int));
        recvn(netfd,train.data,train.len);
        //判断密文
        // char* passwd =(char*)malloc(sizeof(1024));
        if(train.len > 510){
            printf("warning  programe need check\n");
        }
        memcpy(passwd,train.data,train.len);
        if(strcmp(sp->sp_pwdp,passwd)==0){
            char ret[10] = "SUCCESS";
            int len = 8;
            write(netfd,&len,sizeof(int));
            write(netfd,ret,len);
            break;
        }else{
            char ret[10] = "FAIL";
            int len = 5;
            write(netfd,&len,sizeof(int));
            write(netfd,ret,len);
            printf("验证失败\n");
        }
    }
    return 0;
}
